﻿using AutoMapper;
using MediatR;
using SCM.API.Write.Application.Command.Sale;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Implement;
using SCM.Infrastructure.Interface;
using System.Security.Claims;
using Warehouse.Domian.Model;

namespace SCM.API.Write.Application.Handler.Sale
{
    public class AddSaleHandler : IRequestHandler<AddSaleCommand, APIResult<int>>
    {
        IMapper mapper;
        DatabaseContext db;
        ILogger<AddSaleHandler> logger;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public AddSaleHandler(IMapper mapper, DatabaseContext db, ILogger<AddSaleHandler> logger, IHttpContextAccessor httpContextAccessor)
        {
            this.mapper = mapper;
            this.db = db;
            this.logger = logger;
            _httpContextAccessor = httpContextAccessor;
        }

        public async Task<APIResult<int>> Handle(AddSaleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                APIResult<int> result = new APIResult<int>();
                var model = mapper.Map<SaleManagementModel>(request);


                //获取创建人id
                //var userIdClaim = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
                //if (!int.TryParse(userIdClaim, out int userId))
                //{
                //    result.Code = APIEnum.Fail;
                //    result.Msg = "无法获取有效的用户ID";
                //    return await Task.FromResult(result);
                //}
                //model.MadeName = userId;
                //model.MadeTime = DateTime.Now;
                //model.UpdateName = null;
                //model.CreateTime = null;

                var purchas = db.SqlSugar.Queryable<SaleManagementModel>().Where(c => c.SaleId == request.SaleId && !c.IsDel).Count();
                if (purchas > 0)
                {
                    logger.LogError("销售编号唯一");
                    result.Code = APIEnum.Fail;
                    result.Msg = "销售编号唯一";
                    return await Task.FromResult(result);
                }
                var stock = await db.SqlSugar.Queryable<Stocking>().Where(c => c.ProductId == request.ProductId).FirstAsync();
                if (stock != null && stock.IncomingQuantity == 0)
                {

                    result.Code = APIEnum.Fail;
                    result.Msg = $"产品{request.ProductId}没有库存，请及时采购";
                    result.Data = 0;
                    return await Task.FromResult(result);

                }
                if (request.State < 1 || request.State > 3)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "状态值只能为1~3";
                    result.Data = 0;
                    return await Task.FromResult(result);
                }
                int r = db.SqlSugar.Insertable(model).ExecuteCommand();
                if (r > 0)
                {
                    result.Msg = "添加销售管理信息成功";
                    result.Data = r;
                    result.Code = APIEnum.Success;
                }
                else
                {
                    result.Msg = "添加销售管理信息失败";
                    result.Data = r;
                    result.Code = APIEnum.Fail;
                }
                return await Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message, "处理销售添加时发生异常");
                throw;
            }
        }
    }
}
